package com.example.groudChat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.text.SimpleDateFormat;

public class GroupChatServerHandler   extends SimpleChannelInboundHandler<String> {
    //定义一个channel组，管理所有的channnel
    //单例的全局事件组
    private  static ChannelGroup channelGroup=new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

         SimpleDateFormat sim=  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

         //一旦连接立即执行
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        //该方法会自动的轮询所有的channelGoup的客户端并发送消息
        channelGroup.writeAndFlush("[客户端]"+channel.remoteAddress()+"加入聊天");
        channelGroup.add(channel);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress()+"离线了——————");
    }

    //触发这个，就会把cahnnel从group离开
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.writeAndFlush("[客户端]"+channel.remoteAddress()+"离开了");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String msg) throws Exception {

        Channel channel = channelHandlerContext.channel();
        channelGroup.forEach(ch->{
            if(ch!=channel){
                ch.writeAndFlush("[客户]"+channel.remoteAddress()+"发送消息"+msg+"\n");
            }else{
                ch.writeAndFlush("我发送了消息给我自己：  "+msg);
            }
        });
    }
}
